const http = require("http");
const fs= require("fs");

http.createServer((req,res)=>{
    if(req.url =='/'){
        var fileContent = fs.readFileSync("./upload.html");
        res.writeHead(200,{"Content-Type":"text/html,charset=utf-8"});
        res.end(fileContent);
    }else if(req.url=='/upload'){  
        var str ="";
        req.setEncoding("binary");
        req.on("data",(chunk)=>{
            str+=chunk;
        })
        req.on("end",()=>{
            var arr = str.split("\r\n");
            var imgArr = arr.slice(4,arr.length-2);
            var imgStr = imgArr.join("\r\n");
            var buf = Buffer.from(imgStr,"binary");
            fs.writeFileSync("./img/1.png",buf,{"encoding":"binary"});
        })
    }
}).listen(8081)